﻿using System;
using System.Web;
using iTeamyou.LTS.Core.Models;
using iTeamyou.LTS.Core.Utils;

namespace iTeamyou.LTS.Core.Services
{
	public class SSOLoginService : ILoginService<LoginUser>
	{
        public SSODBContext _dbContext;

        public SSOLoginService(SSODBContext dbContext)
		{
            _dbContext = dbContext;
        }

        public LoginUser? Login(string appCode, string token)
        {
            if (string.IsNullOrEmpty(token) || string.IsNullOrEmpty(appCode))
                return null;

            token = HttpUtility.UrlDecode(token).Replace(" ","+");
            var loginUser = new LoginUser();
            var app = _dbContext.Apps.Where(a => a.AppCode == appCode && a.IsEnabled == true).FirstOrDefault();
            if (app != null)
            {
                var user = SecurityHelper.DESDecrypt(token, app.AppSecret);
                var result = _dbContext.LoginUsers.Where(u => u.Id == user && u.AppCode == appCode).FirstOrDefault();
                if (result != null)
                    loginUser = result;

                if (string.IsNullOrEmpty(loginUser.Id))
                    loginUser.Id = user;

                if (string.IsNullOrEmpty(user))
                    return null;

                return loginUser;
            }
            return null;
        }
    }
}

